<template>
    
    <div>
        <!-- 添加课程 -->
        <el-button type="primary" icon="el-icon-check" @click="addCourseForm" class="addCourse">添加课程</el-button>

        <!-- 使用 v-for 循环渲染表单列表 -->
        <el-form v-for="(form, index) in courseForms" :key="index" class="horizontal-form">


            <!-- 课程名 -->
            <el-form-item label="课程名称">
                <el-input type="text" v-model="form.courseName" placeholder="填写课程名称"></el-input>
            </el-form-item>

            <!-- 授课教师 -->
            <el-form-item label="授课教师">
                <el-input type="text" v-model="form.teacherName" placeholder="填写授课教师"></el-input>
            </el-form-item>


            <!-- 所属系部 -->

            <el-form-item label="所属院系">
                <el-select v-model="form.Department_ID" placeholder="请选择" @change="handleDepartmentChange($event , index)">
                    <el-option v-for="item in Departments" :key="item.label" :label="item.label" :value="item.department_ID"></el-option>
                </el-select>
            </el-form-item>

            <!-- 所属专业 -->

            <el-form-item label="所属专业">
                <el-select v-model="form.major_ID" placeholder="请选择" @change="handleMajorChange($event, index)">
                    <el-option v-for="item in filteredMajors" :key="item.label" :label="item.label" :value="item.major_ID"></el-option>
                </el-select>
            </el-form-item>

            <!-- 年级 -->
            <el-form-item label="所属年级">
                <el-select v-model="form.grade" placeholder="请选择">
                    <el-option v-for="item in setGrade" :key="item.label" :label="item.label" :value="item.label"></el-option>
                </el-select>
            </el-form-item>

            <el-button type="primary" @click="submitCourseForm(index)" v-loading.fullscreen.lock="fullscreenLoading">确认添加</el-button>
            <!-- 删除 -->
            <el-button @click="removeCourseForm(index)">取消</el-button>
        </el-form>

        <!-- 批量添加暂时隐藏 -->
        <!-- <el-button type="primary" @click="addCourseEntry(index)">批量添加</el-button> -->
        
       
    </div>
</template>



<script setup>
    import { ref  , computed , onMounted} from "vue";
    import { useStore  } from 'vuex';
    import { ElMessage } from 'element-plus';

    // 使用 `useStore` 获取 Vuex 的 store 实例
    import createCourse from "@/modules/course/create-course";


    const store = useStore();


    const fullscreenLoading = ref(false);

    


    // 选择年级
    let setGrade = ref([
        { label: 2022, },
        { label: 2023, },
        { label: 2024, },
    ]);

    // 选择星期
    let week = ref(['星期一','星期二' ,'星期三' , '星期四' , '星期五']);

    // 选择第几节课
    let lessons = ref(['第一节','第二节' ,'第三节' , '第四节' , '第五节' ,'第六节']);

    // 选择第几节课
    const Department_ID = ref("01"); // 默认选中部门ID为1

    const major_ID = ref(null);

    // 所属院系
    const Departments =  computed(() => store.state.departments);

    console.log('Departments',Departments);

    // 所属专业
    const majors = computed(() => store.state.majors);
    console.log('majors',majors);


    onMounted(() => {
        store.dispatch('loadDepartments');
        store.dispatch('loadMajors');
    });
    // 筛选出来的专业
    const filteredMajors = computed(() => {
        return majors.value.filter(maj => maj.department_ID ===  Department_ID.value);
    });
    

    let courseForms = ref([]);// 存储所有的表单数据


    onMounted(()=>{
        addCourseForm();
    })

    /**
     * 添加表单
     */
    const addCourseForm = () =>{
        courseForms.value.push({
            courseName: '', // 课程名称
            teacherName: '' ,// 教师姓名
            Department_ID:'' , // 所属院系
            major_ID:'',// 所属专业
            grade:'',// 所属年级
        });
    }

    /**
     * 处理院系变化
     * @param {*} value 
     */
    const handleDepartmentChange = (value ,index) => {
        
        Department_ID.value = value;
        courseForms.value[index].major_ID = '';

        
    }

    /**
     * 处理专业变化
     * @param {*} value 
     * @param {*} formIndex 
     */
    const handleMajorChange = (value, formIndex) => {
        console.log('courseForms.value[formIndex]===',courseForms.value[formIndex]);
        // 在这里可以做一些操作，例如更新表单数据中的专业信息
        courseForms.value[formIndex].major_ID = value;
    }


    // 移除
    const removeCourseForm = (index) => {

        console.log('Before removing:', courseForms.value);

        // 移除指定索引的表单
        courseForms.value.splice(index, 1);

        console.log('index===',index);

        // 清空表单内容
        clearForm(index);
    }


    /**
     * 清空表单数据
     * @param { Number } index 下标 
     */
    const clearForm = (index) => {

        console.log('courseForms.value',courseForms.value);

        if (courseForms.value[index]) {

            courseForms.value[index].courseName = '';
            courseForms.value[index].teacherName = '';
            courseForms.value[index].Department_ID = '';
            courseForms.value[index].major_ID = '';
            courseForms.value[index].grade = '';

        }else{
            // console.error(`Error: Unable to clear form at index ${index}. Form item does not exist.`);
        }
    }

    /**
     * 校验表单
     * @param {*} formData 
     */
     function validateCourseFormData(formData) {
        const requiredFields = [
            "courseName",
            "teacherName",
            "major_ID",
            "Department_ID",
            "grade"
        ];

        for (let field of requiredFields) {
            if (!(field in formData) || formData[field] === null || formData[field] === undefined || formData[field] === '') {
                return false;
            }
        }

        return true;
    }

    /**
     * 提交单挑数据
     * @param { Number } index 下标
     */

    const submitCourseForm = (index) =>{

        fullscreenLoading.value = true;

        // 验证表单数据
        if (!validateCourseFormData(courseForms.value[index])) {
            ElMessage.warning({
                message: "请填写全部内容",
                type: "warning",
            });
            fullscreenLoading.value = false;
            return;
        }


        console.log(courseForms.value[index]);


        fullscreenLoading.value = true;

        // 发送请求
        createCourse({
            courseName : courseForms.value[index].courseName,
            grade : courseForms.value[index].grade,
            major_ID : courseForms.value[index].major_ID,
            Department_ID : courseForms.value[index].Department_ID,
            teacherName : courseForms.value[index].teacherName,
        }).then(res=>{
            
            fullscreenLoading.value = false;

            if(res.success){
                ElMessage.success({
                    message: `成功添加${courseForms.value[index].courseName}课程`,
                    type: "success",
                });
            // 添加成功之后删除
            removeCourseForm(index);
            }else{
                ElMessage.warning({
                    message: "请按照正确格式填写全部内容",
                    type: "warning",
                });
            }
        })

    }

    /**
     * 批量添加
     * @param {*} index 
     */
    const addCourseEntry = (index) => {

        fullscreenLoading.value = true;
        debugger
        try {
            createCourse(
                courseForms.value
            ).then(res =>{

                if(res){

                    fullscreenLoading.value = false;

                    if(res.success){
                        ElMessage.success({
                            message: `成功添加课程`,
                            type: "success",
                        });

                    }else{
                        ElMessage.warning({
                            message: res.error,
                            type: "warning",
                        });
                    }

                }
                
            })
        } catch (error) {
            fullscreenLoading.value = false;
            ElMessage.error({
                message: error.error,
                type: "error",
            });
                    
        }
    }

</script>



<style scoped lang="scss">
    .horizontal-form {
        display: flex;
        flex-wrap: wrap; /* 如果需要换行的话 */
    }

    .horizontal-form .el-form-item {
        width: 16%; /* 或者根据需要调整每个表单项的宽度 */
        padding-right: 10px; /* 可选的间距调整 */
        box-sizing: border-box; /* 确保边框和内边距不会增加宽度 */
    }

    .addCourse{
        margin: 20px 0px;
    }
</style>


